<?php
namespace plugin\ky_black\app\admin\model;

use support\Model;

class ProductCategory extends Model
{
    protected $table = 'ky_product_category';
    protected $primaryKey = 'category_id';
    
    protected $fillable = [
        'name',
        'parent_id',
        'level',
        'sort',
        'status',
        'icon',
        'description'
    ];

    /**
     * 获取父级分类
     */
    public function parent()
    {
        return $this->belongsTo(self::class, 'parent_id', 'category_id');
    }

    /**
     * 获取子分类
     */
    public function children()
    {
        return $this->hasMany(self::class, 'parent_id', 'category_id');
    }

    /**
     * 获取分类树形结构
     */
    public static function getCategoryTree($parentId = 0)
    {
        $categories = self::where('parent_id', $parentId)
            ->where('status', 1)
            ->orderBy('sort', 'desc')
            ->orderBy('category_id', 'asc')
            ->get();

        foreach ($categories as $category) {
            $category->children = self::getCategoryTree($category->category_id);
        }

        return $categories;
    }

    /**
     * 获取所有父级分类ID
     */
    public function getParentIds()
    {
        $parentIds = [];
        $parent = $this->parent;
        
        while ($parent) {
            $parentIds[] = $parent->category_id;
            $parent = $parent->parent;
        }

        return array_reverse($parentIds);
    }

    /**
     * 获取所有子分类ID
     */
    public function getChildrenIds()
    {
        $childrenIds = [];
        $children = $this->children;
        
        foreach ($children as $child) {
            $childrenIds[] = $child->category_id;
            $childrenIds = array_merge($childrenIds, $child->getChildrenIds());
        }

        return $childrenIds;
    }
} 